package com.hengxinguotong.zhihuichengjian.net;



import com.hengxinguotong.zhihuichengjian.exception.Excep;
import com.hengxinguotong.zhihuichengjian.exception.LocalException;

import java.net.ConnectException;
import java.net.UnknownHostException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by pc on 2018/1/24.
 */

public abstract class SimpleObserver<T> implements Observer<T>
{
    private Disposable disposable = null;

    @Override
    public void onSubscribe(Disposable d)
    {
        disposable = d;
    }

    @Override
    public void onNext(T t)
    {
        onSuccess(t);
        onComplete();
    }

    @Override
    public void onError(Throwable e)
    {
        if (e instanceof ConnectException || e instanceof UnknownHostException)
        {
            onFail(new LocalException(Excep.CONNECT.getValue()));
        } else
        {
            onFail(e);
        }
    }

    @Override
    public void onComplete()
    {
        if (disposable != null && !disposable.isDisposed())
        {
            disposable.dispose();
        }
    }

    public abstract void onSuccess(T t);

    public abstract void onFail(Throwable e);
}
